
import { sm3, sm2 } from 'sm-crypto';
const { CUSTOM_ENV } = process.env;

const pubkey =
  '039e4e357cf4fd771334f7bca8e152305b83a864c8862302283fd1a39519fdd8a2'; // 加

function SM2EncryptVal(params) {
  return '04' + sm2.doEncrypt(params.toString(), pubkey, 1);
}

// get请求参数拼接
export function transformParams(params = {}) {
  const parts = [];
  Object.keys(params).forEach((key) => {
    const val = params[key];
    let temp = null;
    if (val !== null && typeof val !== 'undefined') {
      if(CUSTOM_ENV == 'safe' || CUSTOM_ENV == 'pre') {
        temp = `${key}=${SM2EncryptVal(val)}`;
      } else {
        temp = `${key}=${val}`
      }
      parts.push(temp);
    }
  });
  return parts.join('&');
}

/** 接口防重 */
export function AntiGravity() {
  return null;
}


function hashcode(str) {
  var hash = 0,
    i,
    chr,
    len;
  if (str.length === 0) return hash;
  for (i = 0, len = str.length; i < len; i++) {
    chr = str.charCodeAt(i);
    hash = (hash << 5) - hash + chr;
    hash |= 0; // Convert to 32bit integer
  }
  return hash;
}


export function getQueryValue(queryName) {
  const url = window.location.href;
  let p = url.split('?')[1];
  let params = new URLSearchParams(p);
  const ticket = params.get(queryName);
  return ticket
};

/** 现场开发环境地址  */
const ISCUrl = window.getIscUrl;

/** 根据不同环境获取对应地址 */
export function getEnvURL() {
  const { origin } = window.location;
  return ISCUrl + origin;
}
// export function getEnvURL() {
//   const { origin } = window.location;
//   let url = null;
//   if (CUSTOM_ENV !== 'devsafe') {
//     url = ISCUrl + origin;
//   }
//   return url;
// }

export const windowObj = [
  { key: 1, name: 'location' },
  { key: 2, name: 'href' },
  { key: 3, name: 'origin' }
]

export const Cookie = {
  set: function (key, value, extime, path) {
    //校验Key, key中不能有等号【=】
    if (key.indexOf('=') !== -1) {
      throw new Error('Cookie不支持key中使用等号【=】, key:' + key);
    }
    let exdate = new Date(); // 获取时间
    exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 ); // 保存的天数
    // 字符串拼接cookie
    // eslint-disable-next-line camelcase
    window.document.cookie =
      key + '=' + value + ';path='+ path +';expires=' + exdate.toGMTString();
  },

  get: function (key) {
    if (document.cookie.length > 0) {
      // 这里显示的格式需要切割一下自己可输出看下
      var arr = document.cookie.split('; ');
      for (let i = 0; i < arr.length; i++) {
        let arr2 = arr[i].split('='); // 再次切割
        // 判断查找相对应的值
        if (arr2[0] === key) {
          var value = arr2[1];
          for (let j = 2; j < arr2.length; j++) {
            value += '=' + arr2[j];
          }
          return value;
        }
      }
    }
  },

  remove: function (key) {
    Cookie.set(key, null, -1);
  },
};
